package com.vip.jwt.common.utils.goeasy;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.goeasy.GoEasy;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * GoEasy服务器请求数据工具类
 */
public class GoEasyUtil {

    @Getter
    private static String REGION_HOST;

    @Getter
    private static String APP_KEY;

    @Getter
    private static String SECRET_KEY;

    @Value("${go-easy-regionhost}")
    public void setAppId(String regionHost) {
        REGION_HOST = regionHost;
    }

    @Value("${go-easy-appkey}")
    public void setAppSecret(String appKey) {
        APP_KEY = appKey;
    }

    @Value("${go-easy-secretkey}")
    public void setSecretKey(String secretKey){
        SECRET_KEY = secretKey;
    }

    /**
     * GoEasy
     * @return
     */
    @Bean
    public GoEasy goEasy(){
        return new GoEasy(REGION_HOST,APP_KEY);
    }

    /**
     * 获取GoEasyOTP
     * @return
     */
    public static String getGoEasyOTP(){
        try {
            String otp = "000" + System.currentTimeMillis();
            SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            byte[] otpBytes = otp.getBytes();
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedOTP = cipher.doFinal(otpBytes);
            otp = Base64.encode(encryptedOTP);
            return otp;
        } catch (Exception e) {
            throw new IllegalStateException("Failed to generate GoEasy-OTP.", e);
        }
    }

    /**
     * 请求获取在线列表
     * @return
     */
    public static String getClientList(String channel){
        String url = "https://"+REGION_HOST+"/herenow?appkey="+APP_KEY+"&channel="+channel;
        return HttpRequest.get(url).execute().body();
    }

    /**
     * 获取客户端在线数量
     * @return
     */
    public static Integer getClientAmount(String channel){
        String url = "https://"+REGION_HOST+"/herenow?appkey="+APP_KEY+"&channel="+channel;
        String str = HttpRequest.get(url).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(str);
        Integer code = jsonObject.getInt("code");
        Integer clientAmount = 0;
        if(code==200){
            JSONObject contentObj = jsonObject.getJSONObject("content");
            JSONObject channelsObj = contentObj.getJSONObject("channels");
            JSONObject channelObj = channelsObj.getJSONObject(channel);
            clientAmount = channelObj.getInt("clientAmount");
        }
        return clientAmount;
    }

}
